package com.mk.magic_c.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @author 孔德成
 * @slogan 致敬大师，致敬未来的你
 * @date 2021/9/28 2:50 上午
 * @desc 发送邮件客户端
 */
@Component
@Slf4j
public class MailClient {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    public void sendMail(String to, String subject, String content) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            // 支持html格式的内容
            helper.setText(content, true);
            log.debug("start send mail -> " + to);
            mailSender.send(helper.getMimeMessage());
            log.debug("send mail success -> " + to);
        } catch (MessagingException e) {
            log.error("send mail fail -> ", e);
        }

    }
}
